package de.dlrg.wms.gui.forms.customForms;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TableItem;

import de.dlrg.wms.gui.forms.generic.AbstractTableView;
import de.dlrg.wms.gui.views.coulmnNames.CurrentRunColumnNames;
import de.dlrg.wms.model.Run;
import de.dlrg.wms.model.SwimmerTrackRun;

import static de.dlrg.wms.gui.views.coulmnNames.CurrentRunColumnNames.*;

public class CurrentRunComposite extends AbstractTableView {
	private Run currentRun;

	public Run getCurrentRun() {
		return currentRun;
	}

	public void setCurrentRun(Run currentRun) {
		this.table.clearAll();
		this.table.setItemCount(0);
		this.currentRun = currentRun;
		this.refresh();
	}

	public CurrentRunComposite(Composite arg0, int arg1) {
		super(arg0, arg1);
		this.tableColumns = CurrentRunColumnNames.class;
		this.initGUI(shell);
	}

	public List<SwimmerTrackRun> getSelectedSwimmerTrackRun() {
		List<SwimmerTrackRun> swimmerTrackRuns = new ArrayList<SwimmerTrackRun>();
		for(TableItem selection : this.table.getSelection()) {
			swimmerTrackRuns.add((SwimmerTrackRun) selection.getData());
		}
		return swimmerTrackRuns;
	}

	@Override
	public void refresh() {
		if (this.currentRun != null) {
			boolean first = true;
			boolean allReady = this.currentRun.checkAllSwimmerReady();
			for (SwimmerTrackRun swimmerTrackRun : this.currentRun
					.getSwimmerTrackRun()) {
				TableItem swimmerTrackRunTableItem = new TableItem(table,
						SWT.NULL);
				{
					swimmerTrackRunTableItem.setText(
							AGE_CLASS_COLUMN.ordinal(), swimmerTrackRun
									.getSwimmer().getAgeClass().getName());
					swimmerTrackRunTableItem
							.setText(SWIMMER_COLUMN.ordinal(), swimmerTrackRun
									.getSwimmer().getName()
									+ ", "
									+ swimmerTrackRun.getSwimmer().getSurName());
					swimmerTrackRunTableItem.setText(DISCIPLINE_COLUMN
							.ordinal(), swimmerTrackRun.getDiscipline()
							.getName());
					swimmerTrackRunTableItem.setText(TRACK_COLUMN.ordinal(), ""
							+ swimmerTrackRun.getTrack().getTrackNumber());

					Display display = Display.getCurrent();
					org.eclipse.swt.graphics.Color blue = display
							.getSystemColor(SWT.COLOR_GRAY);
					org.eclipse.swt.graphics.Color green = display
							.getSystemColor(SWT.COLOR_GREEN);
					if (allReady) {
						if (swimmerTrackRun.isStopped()) {
							swimmerTrackRunTableItem.setBackground(green);
						}
					} else {
						if (!swimmerTrackRun.isReady() && first) {
							swimmerTrackRunTableItem.setBackground(blue);
							first = false;
						}
					}
					swimmerTrackRunTableItem.setText(TIME_COLUMN.ordinal(), ""
							+ swimmerTrackRun.getTime());
					swimmerTrackRunTableItem.setData(swimmerTrackRun);
				}
			}
		}
	}

}
